function labelIdx = getBootstrappedTrainset(L,m)
% labelIdx = getBalancedTrainset(L)
% L - labels different from zero
% m (optional) maximum number of samples per class
% returns vector labelIdx with indices from L for bootstrap

classes = setdiff(unique(L),0); % ignore zero labels
nClasses=length(classes);
NLabel = zeros(1,nClasses);

idx=cell(1,nClasses);
for k=1:nClasses,
    idx{k}=find(L==classes(k));
    NLabel(k)=length(idx{k});
end

[n maxCond]=sort(NLabel,'descend');

if nargin>1 && ~isempty(m) && m>0,
    n(1)=min(n(1),m);
end

n(n>n(1))=n(1);

labelIdx = zeros(1,sum(n(1)-n));
count=1;
for k=1:length(n),
        numberOfNewSamples = n(1)-min(n(1),NLabel(k));
        randIdx=round(rand(1,numberOfNewSamples)*(NLabel(k)-1))+1;
        labelIdx(count:count+numberOfNewSamples-1) = idx{k}(randIdx);
        count = count + numberOfNewSamples;
end


